#include "../include/kc.h"
#include "../include/video.h"
#include "../include/defs.h"
#include "../include/kasm.h"
#include "../include/syscalls.h"

int
atoi(char * string)
{
	int num=0, len, flag=1, i=1;

	len=strlen(string);
	string+=len-1;

	while(len && flag)
	{
		if(isdigit(*string))
		{
			num+=(*string-'0')*i;
			i*=10;
			len--;
			string--;
		}
		else
			flag=0;
	}
	if(len!=0)
		return -1;

	return num;
}

int
itoaAux(unsigned int num, char * str, int len) {
	int idx;
	if ( (num/10) == 0 ) {
		if (len > 1) {
			*str = num%10+'0';
			return 1;
		}
		return 0;
	}
	idx = itoaAux(num/10, str, len-1);
	if (len > 1) {
		str[idx] = num%10+'0';
		return idx+1;
	}
	return 0;
}
//guarda un numero de hasta len-1 digitos en str
void
itoa(unsigned int num, char * str, int len) {
	int idx;
	idx = itoaAux(num, str, len);
	str[idx] = '\0';
}

//imprime un char
int
putchar(char c) {
	write(FD_STDOUT, &c, 1, 0);

	return c;
}

//imprime un string y devuelve la cantidad que se imprimio
int
printstring(char * str) {
	int i = 0;

	while ( str[i] != '\0' ) {
		i++;
	}
	write(FD_STDOUT, str, i, 0);

	return i;
}

int
getchar() {
	char c;

	if ( read(FD_STDIN, &c, 1, 0) == 0)
		return 0;

	return (int)c;
}

int
getcharNoBlock() {
	char c;

	if ( read(FD_STDIN, &c, 1, O_NONBLOCK) == 0)
		return 0;

	return (int)c;
}

int
inportb(int port) {
	char resp;

	read(port, &resp, 1, 0);

	return resp;
}

int
outportb(int port, char data ) {
	return write(port, &data, 1, 0);
}

void *
memcpy(void *dest, const void *src, int count)
{
	if(count>0 && (dest>=(src+count) || src>=(dest+count)))
		return memmove(dest, src, count);
	return dest;
}

void *
memmove(void *dest, const void *src, int count)
{
	void * aux;

	aux=dest;

	if(!(dest==src || count <= 0 || dest==NULL || src==NULL))
	{
		if(dest<src)
			while(count!=0)
			{
				*(char *)dest++=*(char *)src++;
				count--;
			}
		else
		{
			dest+=count-1;
			src+=count-1;
			while(count!=0)
			{
				*(char *)dest--=*(char *)src--;
				count--;
			}
		}
	}
	return aux;
}

void *
memset(void *dest, unsigned char val, int count)
{
	void * aux;

	aux= dest;

    if(count>0 && dest!=NULL)
    	while(count!=0)
    	{
    		*(char *)dest++= val;
    		count--;
    	}

    return aux;
}

int
strlen(const char *str)
{
	const char * aux;

	aux = str;
	while(*aux!='\0')
		aux++;

	return aux-str;
}

char *
strcpy(char *dest, const char *src)
{
	char * aux;

	aux=dest;
	while(*src!='\0')
		*dest++=*src++;
	*dest='\0';

	return aux;
}

char *
strncpy(char *dest, const char *src, int n)
{
	char * aux;

	aux=dest;
	while(n && *src!='\0')
	{
		*dest++=*src++;
		n--;
	}
	if (n != 0)
		*dest = '\0';

	return aux;
}

int
strcmp(const char *s1, const char *s2)
{
	int aux=0;

	while(!aux && (*s1!='\0' || *s2!='\0'))
		aux=*s1++-*s2++;
	return aux;
}

int
isalpha(char c) {
	return (c >= 'A' && c <='Z') || (c >= 'a' && c <='z');
}

int
isdigit(char c)
{
	return (c>='0' && c<='9');
}

char
toupper(char c) {
	if (c >= 'a' && c <='z') {
		c += 'A' - 'a';
	}
	return c;
}

char
tolower(char c) {
	if (c >= 'A' && c <='Z') {
		c += 'a' - 'A';
	}
	return c;
}

int
strncmp(const char *s1, const char *s2, int n)
{
	int aux=0;

	while(!aux && (*s1!='\0' || *s2!='\0') && n--!=0)
		aux=*s1++-*s2++;
	return aux;
}


/***************************************************************
*setup_IDT_entry
* Inicializa un descriptor de la IDT
*
*Recibe: Puntero a elemento de la IDT
*	 Selector a cargar en el descriptor de interrupcion
*	 Puntero a rutina de atencion de interrupcion
*	 Derechos de acceso del segmento
*	 Cero
****************************************************************/

void setup_IDT_entry (DESCR_INT *item, byte selector, dword offset, byte access,
			 byte cero) {
  item->selector = selector;
  item->offset_l = offset & 0xFFFF;
  item->offset_h = offset >> 16;
  item->access = access;
  item->cero = cero;
}


//FUNCIONES PRINTF, SPRINTF Y AUXILIARES.-------------------------------------
//Sacado de http://www.menie.org/georges/embedded/printf.c, con adaptaciones
//y agregados para nuestro SO.

static void printchar(char **str, int c)
{
	if (str) {
		**str = c;
		++(*str);
	}
	else (void)putchar(c);
}

#define PAD_RIGHT 1
#define PAD_ZERO 2

static int prints(char **out, const char *string, int width, int pad)
{
	register int pc = 0, padchar = ' ';

	if (width > 0) {
		register int len = 0;
		register const char *ptr;
		for (ptr = string; *ptr; ++ptr) ++len;
		if (len >= width) width = 0;
		else width -= len;
		if (pad & PAD_ZERO) padchar = '0';
	}
	if (!(pad & PAD_RIGHT)) {
		for ( ; width > 0; --width) {
			printchar (out, padchar);
			++pc;
		}
	}
	for ( ; *string ; ++string) {
		printchar (out, *string);
		++pc;
	}
	for ( ; width > 0; --width) {
		printchar (out, padchar);
		++pc;
	}

	return pc;
}

/* the following should be enough for 32 bit int */
#define PRINT_BUF_LEN 12

static int printi(char **out, int i, int b, int sg, int width, int pad, int letbase)
{
	static char print_buf[PRINT_BUF_LEN];
	register char *s;
	register int t, neg = 0, pc = 0;
	register unsigned int u = i;

	if (i == 0) {
		print_buf[0] = '0';
		print_buf[1] = '\0';
		return prints (out, print_buf, width, pad);
	}

	if (sg && b == 10 && i < 0) {
		neg = 1;
		u = -i;
	}

	s = print_buf + PRINT_BUF_LEN-1;
	*s = '\0';

	while (u) {
		t = u % b;
		if( t >= 10 )
			t += letbase - '0' - 10;
		*--s = t + '0';
		u /= b;
	}

	if (neg) {
		if( width && (pad & PAD_ZERO) ) {
			printchar (out, '-');
			++pc;
			--width;
		}
		else {
			*--s = '-';
		}
	}

	return pc + prints (out, s, width, pad);
}

static int print(char **out, int *varg)
{
	register int width, pad;
	register int pc = 0;
	register char *format = (char *)(*varg++);
	char scr[2];

	for (; *format != 0; ++format) {
		if (*format == '%') {
			++format;
			width = pad = 0;
			if (*format == '\0') break;
			if (*format == '%') {
				printchar (out, *format);
				++pc;
			}
			if (*format == '-') {
				++format;
				pad = PAD_RIGHT;
			}
			while (*format == '0') {
				++format;
				pad |= PAD_ZERO;
			}
			for ( ; *format >= '0' && *format <= '9'; ++format) {
				width *= 10;
				width += *format - '0';
			}
			if( *format == 's' ) {
				register char *s = *((char **)varg++);
				pc += prints (out, s?s:"(null)", width, pad);
				continue;
			}
			if( *format == 'd' ) {
				pc += printi (out, *varg++, 10, 1, width, pad, 'a');
				continue;
			}
			if( *format == 'x' ) {
				pc += printi (out, *varg++, 16, 0, width, pad, 'a');
				continue;
			}
			if( *format == 'X' ) {
				pc += printi (out, *varg++, 16, 0, width, pad, 'A');
				continue;
			}
			if( *format == 'u' ) {
				pc += printi (out, *varg++, 10, 0, width, pad, 'a');
				continue;
			}
			if( *format == 'c' ) {
				/* char are converted to int then pushed on the stack */
				scr[0] = *varg++;
				scr[1] = '\0';
				pc += prints (out, scr, width, pad);
				continue;
			}
		}
		printchar (out, *format);
		++pc;
	}
	if (out)
		**out = '\0';

	return pc;
}

int printf(const char *format, ...)
{
	register int *varg = (int *)(&format);
	return print(0, varg);
}

int sprintf(char *out, const char *format, ...)
{
	register int *varg = (int *)(&format);
	return print(&out, varg);
}

//----------------------------------------------------------------------------

